package org.mspring.mlog.web.security.interceptors;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;

import org.mspring.mlog.web.security.SecurityUtils;
import org.mspring.mlog.web.security.interceptors.handlers.AbstractFailureHandler;
import org.mspring.mlog.web.security.interceptors.handlers.RedirectFailureHandler;
import org.mspring.platform.utils.StringUtils;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.util.AntPathRequestMatcher;
import org.springframework.security.web.util.RequestMatcher;

/**
 * 用户后台访问的权限控制
 * 
 * @author Gao Youbo
 * @since 2013年7月11日
 */
public class AdminSecurityInterceptor extends AbstractSecurityInterceptor {

    /**
     * 登录失败跳转地址
     */
    private String failureUrl;
    /**
     * 不进行过滤的请求,用逗号分割
     */
    private String unValidateUrls;

    public String getFailureUrl() {
        return failureUrl;
    }

    public void setFailureUrl(String failureUrl) {
        this.failureUrl = failureUrl;
    }

    public String getUnValidateUrls() {
        return unValidateUrls;
    }

    public void setUnValidateUrls(String unValidateUrls) {
        this.unValidateUrls = unValidateUrls;
    }

    @Override
    public boolean exec(FilterInvocation fi) throws IOException, ServletException {
        // TODO Auto-generated method stub
        HttpServletRequest request = fi.getRequest();

        RequestMatcher urlMatcher = new AntPathRequestMatcher("/admin/**");
        if (urlMatcher.matches(request)) {
            boolean flag = SecurityUtils.hasAdminAccessToken(request);
            if (flag) {
                return true;
            }
            if (StringUtils.isNotBlank(unValidateUrls)) {
                String[] arr = StringUtils.split(unValidateUrls, ",");
                RequestMatcher unValidateMatcher = null;
                for (String unValidateUrl : arr) {
                    unValidateMatcher = new AntPathRequestMatcher(unValidateUrl);
                    if (unValidateMatcher.matches(request)) { // 如果请求的地址在不进行权限验证的地址列表中，跳出验证
                        return true;
                    }
                }
            }
            return false;
        }
        return true;
    }

    @Override
    protected AbstractFailureHandler getNativeFailureHandler(FilterInvocation fi) {
        // TODO Auto-generated method stub
        if (StringUtils.isNotBlank(this.failureUrl)) {
            RedirectFailureHandler failureHandler = new RedirectFailureHandler();
            failureHandler.setRedirectUrl(fi.getRequest().getContextPath() + failureUrl);
            return failureHandler;
        }
        return null;
    }

}
